<?php
namespace App\Http\Controllers\Admin;

#use App\Http\Controllers\AdminController as Controller;
use App\Http\Controllers\Controller as Controller;
use Crypt;
use Illuminate\Http\Request;
use App\Model\User;
use App\Model\Admin;

class AuthController extends Controller{
	
	
	/**
	 * 后台管理员登录
	 * @return \Illuminate\View\View|\Illuminate\Contracts\View\Factory|unknown
	 * @author zhuyiqi
	 */
	public function login(){
		#dd( encode_passwd('admin123'));
		if(!request()->ajax()){
			if(isset($this->admin['id']) && !empty($this->admin['id'])) return redirect('/home');
			return view('Admin.Auth.login');
		}
		$input = request()->only(['name', 'passwd', 'captcha']);
		if(session('login_captcha') != md5($input['captcha'])){
			session()->forget('login_captcha');
			return ajaxreturn(0,trans('validation.wrong_captcha'));
		}
		

		$admin = Admin::where('username', $input['name'])->first();
		
		if(!$admin){ return ajaxreturn(0,'非管理用户'); }
		
		if(md5($input['passwd']) != $admin->password){
			return ajaxreturn(0,trans('validation.login_err'));
		}
		
		// 重置session
		session()->forget('admin');
		session()->put([
				'admin' => [
						'id' => $admin->id,
						'name' => $admin->name,
						'rights' => explode('|', $admin->rights),
						'article_cats'=>empty($admin['article_cats'])?[]:json_decode($admin['article_cats']),
                		'video_cats'=>empty($admin['video_cats'])?[]:json_decode($admin['video_cats']),
				]
		]);
		
		//admin_log(['msg'=>$user->user_name.'登录了系统']);
		return ajaxreturn( 1, '登录成功，请等待跳转');
	}
	
	/**
	 * 管理员注销
	 * @author zhuyiqi
	 */
	public function logout(){
		session()->forget('admin');
		return redirect('/Auth/login');
	}
	

	/**
	 * 获取验证码
	 * @return unknown
	 * @author zhuyiqi
	 */
	public function captcha(){
		return response(create_captcha('captcha', 'login'))->header('Content-type', 'image/png');
	}
}